layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var _companyId = $.cookie("companyId");
    //列表数据
    var option = {
        elem: '#tableList',
        url : '/produce/pageByCreateBy?createBy='+_companyId,
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50,style:'height:50px;'},
            {field: 'name', title: '产品名称', minWidth:100, align:"center"},
            {field: 'pic', title: '产品图片', minWidth:200,style:'height:50px;', align:'center',templet:function(d){
                    if (d.pic != null && d.pic != "") {
                        //处理图片
                        var picArr = d.pic.split(";");
                        return '<img src="'+ picArr[0] +'" width="50" />';
                    }else {
                        return '';
                    }
                }},
            {field: 'price', title: '产品单价', minWidth:100, align:"center"},
            {field: 'categoryId', title: '所属类型',  align:'center', templet:function(d){
                    var typeName = "";
                    $.ajax({
                        url : '/produce/category/' + d.categoryId,
                        async:false,
                        success: function (data) {
                            typeName = data.name;
                        }
                    });
                    return typeName == null?'':typeName;
                }
            },
            {title: '操作', minWidth:200, templet:'#tableListBar',fixed:"right",align:"center"}
        ]]
    };

    //产品分类数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            option.url = '/produce/query';
            option.where = {categoryId: item.id,createBy: _companyId};
            table.render(option);
        },
        nodes:null
    };
    //异步加载产品所处产品分类数据
    $.get('/produce/category/treeByCreateBy?createBy='+_companyId,function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
        }
        treeData.nodes = data.data;
        layui.tree(treeData);
    });

    //产品列表
    var tableIns = table.render(option);

    //搜索产品信息
    $(".search_btn").on("click",function(){
        var searchKey = $(".searchVal").val();
        if(searchKey != ''){
            option.url = '/produce/query';
            option.method = 'post';
            option.where = {name: searchKey,createBy: _companyId};
            table.render(option);
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //添加产品
    $(".addBtn").click(function(){
        var index = layui.layer.open({
            title : "添加产品",
            type : 2,
            content : "produceAdd",
            area: ['100%',$(document).height() + 'px'],
            success : function(layero, index){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回产品列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        });
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('listTable'),//此处的id为table数据格式中的id
            data = checkStatus.data,
            idArr = [];
        if(data.length > 0) {
            for (var i in data) {
                idArr.push(data[i].id);
            }
            layer.confirm('确定删除选中的产品？', {icon: 3, title: '提示信息'}, function (index) {
                for(var i=0;i<idArr.length;i++){
                    $.get("/produce/delete?id=" + idArr[i],function(data){
                        if (data.code == 200) {
                            layer.msg("删除成功！");
                        } else {
                            layer.msg("删除失败，请重试！");
                        }
                        tableIns.reload();
                        layer.close(index);
                    });
                }
            })
        }else{
            layer.msg("请选择需要删除的产品");
        }
    });

    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "修改产品信息",
                type : 2,
                content : "produceEdit?id=" + data.id,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回产品列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }else if(layEvent === 'config') { //配置产品规格信息
            var index = layui.layer.open({
                title: "产品配置",
                type: 2,
                content: "config/configIndex?id=" + data.id,
                area: ['100%',($(document).height() - 40) + 'px'],
                success: function () {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回产品列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此产品？',{icon:3, title:'提示信息'},function(index){
                $.get("/produce/delete?id=" + data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

});